package com.szhuima.imessage.channel;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.szhuima.imessage.channel.Constants.DEFAULT_BIND_PORT;
import static com.szhuima.imessage.channel.NettyEventLoopFactory.serverSocketChannelClass;

/**
 * * @Author: Martin(微信：martin-jobs)
 * * @Date    2025/2/27 21:48
 * * @Description
 * * @Github <a href="https://github.com/mardingJobs">Github链接</a>
 **/
public class WebsocketServer extends AbstractServer {

    private static final Logger logger = LoggerFactory.getLogger(WebsocketServer.class);

    private EventLoopGroup bossGroup;

    private EventLoopGroup workerGroup;


    @Override
    public void doOpen() {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bossGroup = NettyEventLoopFactory.eventLoopGroup(1, "NettyServerBoss");
        workerGroup = NettyEventLoopFactory.eventLoopGroup(0, "NettyServerWorker");
        bootstrap.group(bossGroup, workerGroup)
                .channel(serverSocketChannelClass())
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {

                    }
                });

        ChannelFuture channelFuture = bootstrap.bind(DEFAULT_BIND_PORT);
        channelFuture.syncUninterruptibly();
        Channel channel = channelFuture.channel();

        channel.closeFuture().syncUninterruptibly();
    }


    @Override
    public void shutdown() {
        if (bossGroup != null && !bossGroup.isShuttingDown()) {
            bossGroup.shutdownGracefully();
        }
        if (workerGroup != null && !workerGroup.isShuttingDown()) {
            workerGroup.shutdownGracefully();
        }
    }
}
